package univer.oko.database.rmi.impl;

import univer.oko.Error;

import java.util.Vector;

/**
 * @author Eduard Dudar
 *         Date: 19.11.2005
 *         Time: 1:43:51
 */
public class SpecialityImpl extends ImplHelper implements DBMetadata {
    public SpecialityImpl(RMIImpl rmi) {
        super(rmi);
    }

    public synchronized int addSpeciality(String name, String direction) {
        if (this.isOccurs(SELECT + SPECIALITY_ID + FROM + SPECIALITY + WHERE + SPECIALITY_NAME + " = '" + name + "'")) {
            return univer.oko.Error.REPEAT;
        }

        int count = this.getIntValue(SELECT + MAX(SPECIALITY_ID) + FROM + SPECIALITY) + 1;
        Integer d = this.getIntValue(SELECT + DIRECTION_ID + FROM + DIRECTION + WHERE + DIRECTION_NAME + " = '" + direction + "'");
        if(d == null)
          return Error.ALRIGHT;
        Integer f = this.getIntValue(SELECT + DIRECTION_REF_FACULTY + FROM + DIRECTION + WHERE + DIRECTION_ID + " = '" + d + "'");
        if(f == null)
          return Error.ALRIGHT;
        this.executeUpdate(INSERT_INTO + SPECIALITY + " values(" + count + "," + f + ",'" + name + "'," + d + ")");
        this.commit();
        return Error.ALRIGHT;
    }

    public synchronized Vector getSpecialities() {
        return this.getVectorValue(SELECT + SPECIALITY_NAME + FROM + SPECIALITY + ORDER_BY + SPECIALITY_NAME);
    }

    public synchronized Vector getSpecialities(String direction) {
        return this.getVectorValue(
                SELECT + SPECIALITY_NAME +
                        FROM + SPECIALITY + ", " + DIRECTION +
                        WHERE + SPECIALITY_REF_DIRECTION + " = " + DIRECTION_ID + AND + DIRECTION_NAME + " = '" + direction + "' " +
                        ORDER_BY + SPECIALITY_NAME);
    }

    public synchronized int deleteSpeciality(String str) {
        if (this.isOccurs(
                SELECT + " [student].[id_student] " +
                        FROM + "[student], " + SPECIALITY +
                        WHERE + SPECIALITY_NAME + " = '" + str + "' " + AND + SPECIALITY_ID + " = [student].[ref_speciality]"))
        {
            return Error.IN_USE;
        }

        if (this.executeUpdate(DELETE_FROM + SPECIALITY + WHERE + SPECIALITY_NAME + " = '" + str + "'")) {
            this.commit();
            return Error.ALRIGHT;
        }

        return Error.SQL_ERROR;
    }

    public synchronized Integer getSpecialityID(String str) {
        return this.getIntValue(SELECT + SPECIALITY_ID + FROM + SPECIALITY + WHERE + SPECIALITY_NAME + " = '" + str + "'");
    }

    public synchronized String getSpecialityName(int id) {
        return this.getStringValue(SELECT + SPECIALITY_NAME + FROM + SPECIALITY + WHERE + SPECIALITY_ID + " = " + id);
    }
}
